<template>
  <!-- class="app-container" -->
  <div>
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
    >
      <el-form-item label="字段" prop="fieldName">
        <el-input
          v-model="queryParams.fieldName"
          placeholder="请输入字段"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="操作符" prop="operation">
        <el-input
          v-model="queryParams.operation"
          placeholder="请输入操作符"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="比较值" prop="compareValue">
        <el-input
          v-model="queryParams.compareValue"
          placeholder="请输入比较值"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="优先级" prop="priority">
        <el-input
          v-model="queryParams.priority"
          placeholder="请输入优先级"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="打标字段" prop="tagField">
        <el-input
          v-model="queryParams.tagField"
          placeholder="请输入打标字段"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="标签名称" prop="tagName">
        <el-input
          v-model="queryParams.tagName"
          placeholder="请输入标签名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="规则分组ID" prop="ruleGroupId">
        <el-input
          v-model="queryParams.ruleGroupId"
          placeholder="请输入规则分组ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="表名" prop="tableName">
        <el-input
          v-model="queryParams.tableName"
          placeholder="请输入表名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['conf:BiRuleSpecifications:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['conf:BiRuleSpecifications:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['conf:BiRuleSpecifications:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['conf:BiRuleSpecifications:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      :data="BiRuleSpecificationsList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="自增id" align="center" prop="id" /> -->
      <el-table-column label="字段类型" align="center" prop="tagType">
        <template slot-scope="scope">
          {{ scope.row.tagType | state1 }}
        </template>
      </el-table-column>
      <el-table-column label="字段" align="center" prop="fieldName" />

      <el-table-column label="操作符" align="center" prop="operation">
        <template slot-scope="scope">
          {{ scope.row.operation | state2 }}
        </template>
      </el-table-column>
      <el-table-column label="比较值" align="center" prop="compareValue" />
      <!-- <el-table-column label="优先级" align="center" prop="priority" />
      <el-table-column label="打标字段" align="center" prop="tagField" />
      <el-table-column label="标签名称" align="center" prop="tagName" />
      <el-table-column label="规则分组ID" align="center" prop="ruleGroupId" /> -->
      <!-- <el-table-column label="是否激活" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isActive"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="表名" align="center" prop="tableName" /> -->
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['conf:BiRuleSpecifications:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['conf:BiRuleSpecifications:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改BI的打标规则对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="550px"
      append-to-body
      v-if="open"
    >
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="字段">
          <!--@change="changecompareValue" <el-input v-model="form.fieldName" placeholder="请输入字段" /> -->
          <el-select v-model="form.tagType" style="width: 120px">
            <el-option label="从表中选" value="table" />
            <el-option label="从变量选" value="variable" />
          </el-select>
          <el-select
            v-model="form.fieldName"
            placeholder="请输入字段"
            clearable
            filterable
            @focus="changecompareValue"
          >
            <el-option
              v-for="(dict, i) in tableNameList"
              :key="i"
              :label="dict.comment"
              :value="dict.field_name"
            />
          </el-select>
          <el-button @click="openvariable = true"> + </el-button>
        </el-form-item>
        <el-form-item label="操作符" prop="operation">
          <el-select v-model="form.operation" @change="changeoperation">
            <el-option label="=" value="=" />
            <el-option label="!=" value="!=" />
            <el-option label=">" value=">" />
            <el-option label=">=" value=">=" />
            <el-option label="<" value="<" />
            <el-option label="<=" value="<=" />
            <el-option label="包含" value="include" />
            <el-option label="不包含" value="exclude" />
            <el-option label="为空" value="isNull" />
            <el-option label="不为空" value="isNotNull" />
          </el-select>
        </el-form-item>
        <!-- 包含: include
不包含: exclude
打标规则中，增加一个compareType: 文本：text/日期控件: date/ 今天：today/
        过去天数: passdays -->
        <el-form-item
          label="比较值"
          prop="compareValue"
          v-if="opencompareValue"
        >
          <el-select
            v-model="form.compareType"
            style="width: 120px"
            @change="handleToday"
          >
            <el-option label="文本框" value="text" />
            <el-option label="日期控件" value="date" />
            <el-option label="今天" value="today" />
            <el-option label="过去天数" value="passdays" />
          </el-select>
          <el-input
            v-show="form.compareType != 'date'"
            v-model="form.compareValue"
            placeholder="请输入比较值"
            style="width: 200px"
            @blur="validateInput(form.compareValue)"
          />
          <el-date-picker
            v-show="form.compareType == 'date'"
            clearable
            v-model="dateValue"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择日期"
            @change="handleDate"
          >
          </el-date-picker>

          <!-- <el-button size="mini" @click="openhandleDate = true"
            >日期选择</el-button
          > -->
        </el-form-item>
        <!-- <el-form-item label="优先级" prop="priority">
          <el-input v-model="form.priority" placeholder="请输入优先级" />
        </el-form-item>
        <el-form-item label="打标字段" prop="tagField">
         
          <el-select
            v-model="form.tagField"
            placeholder="请输入打标字段"
            clearable
            filterable
          >
            <el-option
              v-for="dict in tagNameList"
              :key="dict.field_name"
              :label="dict.comment"
              :value="dict.field_name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="标签名称" prop="tagName">
          <el-input v-model="form.tagName" placeholder="请输入标签名称" />
        </el-form-item>
        <el-form-item label="规则分组ID" prop="ruleGroupId">
          <el-input v-model="form.ruleGroupId" placeholder="请输入规则分组ID" />
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="openhandleDate" append-to-body width="300px">
      <el-date-picker
        clearable
        v-model="compareValue"
        type="date"
        value-format="yyyy-MM-dd"
        placeholder="请选择日期"
        @change="handleDate"
      >
      </el-date-picker>
    </el-dialog>

    <el-dialog
      :visible.sync="openvariable"
      width="90%"
      append-to-body
      v-if="openvariable"
    >
      <BiCalculatorVariables
        :applicationTable="tableName"
        @close="changecompareValue"
      ></BiCalculatorVariables>
    </el-dialog>
  </div>
</template>

<script>
import BiCalculatorVariables from "@/views/conf/BiCalculatorVariables/edit.vue";
import {
  listBiCalculatorVariables,
  getBiCalculatorVariables,
  delBiCalculatorVariables,
  addBiCalculatorVariables,
  updateBiCalculatorVariables,
  variableList,
} from "@/api/conf/BiCalculatorVariables";
import moment from "moment";

import {
  listByAbnormalRule,
  listBiRuleSpecifications,
  getBiRuleSpecifications,
  delBiRuleSpecifications,
  addByRuleTage,
  updateBiRuleSpecifications,
  RuleTagger,
  getTablefieldsWithComments,
  bitableoperation,
  addByAbnormalRule,
} from "@/api/conf/BiRuleSpecifications";
import axios from "axios";
export default {
  name: "BiRuleSpecifications",
  components: {
    BiCalculatorVariables,
  },
  props: {
    row: {
      type: Object,
      default: () => {},
    },

    id: {
      type: Number,
      default: 0,
    },
    tableName: {
      type: String,
      default: "",
    },
    biruletagList: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      // 比较值,正常显示
      opencompareValue: true,
      //弹窗打标变量页面
      openvariable: false,
      tagName: "select",
      dateValue: "",
      compareValue: "input",
      openhandleDate: false,
      tableNameList: [],
      tagNameList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: false,
      // 总条数
      total: 0,
      // BI的打标规则表格数据
      BiRuleSpecificationsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        fieldName: null,
        operation: null,
        compareValue: null,
        priority: null,
        tagField: null,
        tagName: null,
        ruleGroupId: null,
        tableName: null,
      },

      // 表单参数
      form: {
        tagType: "table",
      },
      // 表单校验
      rules: {
        fieldName: [
          { required: true, message: "字段不能为空", trigger: "blur" },
        ],
        operation: [
          { required: true, message: "操作符不能为空", trigger: "blur" },
        ],
        // compareValue: [
        //   { required: true, message: "比较值不能为空", trigger: "blur" },
        // ],
        priority: [
          { required: true, message: "优先级不能为空", trigger: "blur" },
        ],
        tagField: [
          { required: true, message: "打标字段不能为空", trigger: "blur" },
        ],
        tagName: [
          { required: true, message: "标签名称不能为空", trigger: "blur" },
        ],
        ruleGroupId: [
          { required: true, message: "规则分组ID不能为空", trigger: "blur" },
        ],
      },
    };
  },
  watch: {
    row: {
      handler: function (newnew, oldold) {
        console.log("newnew", newnew);
        if (newnew) {
          this.queryParams.id = this.row.id;

          this.tableName = this.row.tableName;
          // this.form.id=newnew
          if (!this.queryParams.id) {
            return;
          }
          this.getList();
          if (this.tableName) {
            this.selectgetTablefieldsWithComments();
          }
        }
        // this.showColumn = newnew;
        // // 这里需要让表格重新绘制一下，否则会产生固定列错位的情况
        // this.$nextTick(() => {
        //   this.$refs.BaseTable.doLayout();
        // });
      },
      deep: true,
      immediate: true,
    },
    // tableName: {
    //   handler(newVal, oldVal) {
    //     console.log(newVal);
    //     if (!this.tableName) {
    //       return;
    //     }

    //     // this.tableName = this.queryParams.tableName;
    //     this.selectgetTablefieldsWithComments();
    //   },
    // },
    biruletagList: {
      handler(newVal, oldVal) {
        console.log(newVal);
        if (this.biruletagList.length == 0) {
          this.BiRuleSpecificationsList = [];
          this.total = 0;
        }
      },
      deep: true,
      immediate: true,
    },
  },
  filters: {
    state1(string) {
      if (string == "variable") {
        return "变量";
      }
      if (string == "define") {
        return "自定义";
      }
      if (string == "table") {
        return "表字段";
      }

      // if (int == 2) { return "审批通过" };:
    },
    state2(string) {
      // 为空：isNull 不为空： isNotNull
      if (string == "isNull") {
        return "为空";
      }
      if (string == "isNotNull") {
        return "不为空";
      }
      if (string == "include") {
        return "包含";
      }
      if (string == "exclude") {
        return "不包含";
      }
      if (string == "=") {
        return "=";
      }
      if (string == "!=") {
        return "!=";
      }
      if (string == ">") {
        return ">";
      }
      if (string == ">=") {
        return ">=";
      }
      if (string == "<") {
        return "<";
      }
      if (string == "<=") {
        return "<=";
      }
    },
  },
  created() {
    // this.getList();
    // let obj = { tableName: "costtable" };
    // let fd = new FormData();
    // fd.append("tableName", "costtable"); // 传文件
    // axios
    //   .get(
    //     process.env.VUE_APP_BASE_API +
    //       "/conf/BiRuleSpecifications/getTablefieldsWithComments",
    //     fd
    //   )
    //   .then((response) => {});
    // return;
  },
  methods: {
    changeoperation() {
      //选择这两项的时候，下面的比较值隐藏，比较值类型带text
      if (
        this.form.operation == "isNull" ||
        this.form.operation == "isNotNull"
      ) {
        this.form.compareType = "text";
        this.form.compareValue = "";
        this.opencompareValue = false;
      } else {
        this.opencompareValue = true;
      }
    },
    validateInput(value) {
      // 使用正则表达式检查输入是否为纯数字
      if (this.form.compareType == "passdays") {
        if (/^\d+$/.test(value)) {
          // this.$modal.msgError("不允许纯数字");
          // value = "";
        } else {
          this.$modal.msgError("请输入有效数字");
        }
      }
    },
    changecompareValue() {
      if (this.form.tagType == "table") {
        this.selectgetTablefieldsWithComments();
      } else if (this.form.tagType == "variable") {
        // this.form.fieldName = "";
        this.getvariableList();
      }
    },
    getvariableList() {
      variableList({ applicationTable: this.tableName }).then((response) => {
        this.tableNameList = [];

        // this.tableNameList = response;
        response.forEach((element) => {
          this.tableNameList.push({
            comment: element.variableName,
            field_name: element.id,
          });
        });
      });
    },
    selectgetTablefieldsWithComments() {
      if (!this.tableName) {
        return;
      }
      getTablefieldsWithComments({ tableName: this.tableName }).then(
        (response) => {
          this.tableNameList = [];
          this.tableNameList = response;
        }
      );
    },
    handleDate(key) {
      // console.log(JSON.stringify(key));
      // return;
      this.form.compareValue = this.dateValue;
      // this.openhandleDate = false;
    },
    handleToday() {
      if (this.form.compareType == "today") {
        this.form.compareValue = "今天";
      }

      this.$forceUpdate();

      // this.form.compareValue = moment(new Date()).format("YYYY-MM-DD");

      // console.log(123);
    },
    /** 查询BI的打标规则列表 */
    getList() {
      this.loading = true;
      listByAbnormalRule(this.queryParams).then((response) => {
        this.BiRuleSpecificationsList = response.rows ? response.rows : [];
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        tagType: "table",
        compareType: "text",
        // fieldName: null,
        // operation: null,
        // compareValue: null,
        // priority: null,
        // tagField: null,
        // tagName: null,
        // ruleGroupId: null,
        // tableName: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加BI的打标规则";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getBiRuleSpecifications(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改BI的打标规则";
        this.changecompareValue();
      });
    },
    // 用户状态修改
    handleStatusChange(row) {
      let text = row.isActive === "0" ? "启用" : "停用";
      this.$modal
        .confirm('确认要"' + text + '"规则吗？')
        .then(function () {
          return updateBiRuleSpecifications({
            id: row.id,
            isActive: row.isActive,
          });
        })
        .then(() => {
          this.$modal.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.isActive = row.isActive === "0" ? "1" : "0";
        });
    },
    /** 提交按钮 */
    submitForm() {
      if (this.form.compareType == "passdays") {
        if (/^\d+$/.test(this.form.compareValue)) {
          // this.$modal.msgError("不允许纯数字");
          // value = "";
          this.form.compareValue = "过去" + this.form.compareValue;
        } else {
          this.$modal.msgError("请输入有效数字");
          return;
        }
      }
      this.form.tableName = this.row.tableName;
      this.form.abnormalTagId = this.row.id;
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateBiRuleSpecifications(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();

              this.form.compareValue = null;
              this.compareValue = "input";
              this.dateValue = "";
            });
          } else {
            addByAbnormalRule(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
            this.form.id = null;
            this.form.compareValue = null;
            this.compareValue = "input";
            this.dateValue = "";
          }
        }
      });
      if (this.form.compareType == "passdays") {
        this.form.compareValue = "";
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除BI的打标规则编号为"' + ids + '"的数据项？')
        .then(function () {
          return delBiRuleSpecifications(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "conf/BiRuleSpecifications/export",
        {
          ...this.queryParams,
        },
        `BiRuleSpecifications_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
